package com.jadefashion.service.impl;

import com.github.wxpay.sdk.WXPayUtil;
import com.jadefashion.health.resources.*;
import com.jadefashion.mapper.MemberMapper;
import com.jadefashion.mapper.OrderMapper;
import com.jadefashion.mapper.OrderSettingMapper;
import com.jadefashion.mapper.SetmealServiceMapper;
import com.jadefashion.pojo.Member;
import com.jadefashion.pojo.Order;
import com.jadefashion.pojo.Setmeal;
import com.jadefashion.service.OrderService;
import com.jadefashion.service.SetmealService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderSettingMapper orderSettingMapper;
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    private SetmealServiceMapper setmealServiceMapper;

    private String appid="wx8397f8696b538317";


    private String partner="1473426802";


    private String partnerkey="T6m9iK73b0kn9g5v426MKfHQH7X8rKwb";

    @Override
    public Map<String, String> findOrderInfo(String orderId) {
        Map<String, String> map=orderMapper.findOrderInfo(orderId);
        return map;
    }



    @Override
    public Map order(Map map) {
        String setmealId = (String) map.get("setmealId");
        String orderDate = (String) map.get("orderDate");
        String phoneNum= (String) map.get("telephone");
        String name= (String) map.get("name");
        String sex=(String) map.get("sex");
        String idCard=(String) map.get("idCard");
        Date regDate=new Date();
        Member member = new Member();
        member.setName(name);
        member.setIdCard(idCard);
        member.setRegTime(regDate);
        member.setPhoneNumber(phoneNum);
        member.setSex(sex);
        //1：先判断是否可预约 t_ordersetting表
        System.out.println("先判断是否可预约");
        int count=orderSettingMapper.isBookableByDate(orderDate);
       if(count==0) {//不可预约。
            throw new RuntimeException("预约已经满了");
        }
        //否则可以预约：
        //2.先判断用户是新用户还是老用户
        System.out.println("先判断用户是新用户还是老用户");
            Integer mid=memberMapper.isNewMember(phoneNum);

       if(mid==null){//新用户
           //成员表添加,需要member参数
           System.out.println("新用户：成员表添加,需要member参数");
           memberMapper.add(member);
       }else { //老用户
            //判断是否已经预约。
           System.out.println("老用户：判断是否已经预约");
            int counOrder=orderMapper.isOrderedByMemberIdAndOrderdateAndSetmealId(mid,orderDate,setmealId);
            if(counOrder>0){  //说明已经预约
//                throw new RuntimeException("请勿重新预约");
               }
       }

         //  //订单表添加。
         Order order = new Order();
         order.setMemberId(member.getId());
         order.setOrderDate(DateUtils.parseString2Date(orderDate));
         order.setOrderType("微信预约");
         order.setOrderStatus("否");
         order.setSetmealId(Integer.valueOf(setmealId));
        try {
            orderMapper.addOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //生成订单号
        IdWorker idworker=new IdWorker();
        String orderNumber=idworker.nextId()+"";
         //生成时间
         Date payDate = new Date();
         //得到套餐信息
         Setmeal setMealDetail = setmealServiceMapper.findSetMealById(Integer.valueOf(setmealId));
         //公司名称
         String business_Name="传智健康有限公司";
         //订单状态
         int orderStatus=0;
         orderMapper.addOrderInfo(orderNumber,payDate,setMealDetail.getName(),setMealDetail.getPrice(),business_Name,member.getId(),orderStatus);

        //3 ordersetting+1
         orderSettingMapper.addReservationsByOrderDate(orderDate);
        Map hashMap = new HashMap();
        hashMap.put("orderId",order.getId());
        hashMap.put("orderNumber",orderNumber);
        hashMap.put("setMealPrice",setMealDetail.getPrice()/100.0);
        return hashMap;
    }

    @Override
    public Integer findOrderStatus(String orderNumber) {
        Integer status=orderMapper.findOrderStatus(orderNumber);
        return status;
    }

    @Override
    public String  createNative(String orderId, String totalPay) {
        //1.创建参数
        Map<String,String> param=new HashMap();//创建参数
        param.put("appid", appid);//公众号
        param.put("mch_id", partner);//商户号
        param.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
        param.put("body", "传智健康支付中心-商品支付");//商品描述
        param.put("out_trade_no", orderId);//商户订单号
        param.put("total_fee",totalPay);//总金额（分）
        param.put("spbill_create_ip", "127.0.0.1");//IP
        param.put("notify_url", "http://ufj2n2.natappfree.cc/order/payNotify.do");//回调地址(随便写)
        param.put("trade_type", "NATIVE");//交易类型
        try {
            //2.生成要发送的xml
            String xmlParam = WXPayUtil.generateSignedXml(param, partnerkey);
            System.out.println(xmlParam);
            HttpClient client=new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            client.setHttps(true);
            client.setXmlParam(xmlParam);
            client.post();
            //3.获得结果
            String result = client.getContent();
            System.out.println(result);
            Map<String, String> resultMap = null;
            try {
                resultMap = WXPayUtil.xmlToMap(result);
            } catch (Exception e) {
                throw new RuntimeException("微信下单失败", e);
            }


            // 检查业务状态
            String returnCode = resultMap.get("return_code");
            if ("FAIL".equals(returnCode)) {
                throw new RuntimeException("【微信支付】微信支付业务失败");
            }
            String resultCode = resultMap.get("result_code");
            if ("FAIL".equals(resultCode)) {
                throw new RuntimeException("【微信支付】微信支付业务失败");
            }

            // 下单成功，获取支付链接
            String url = resultMap.get("code_url");
            if (StringUtils.isBlank(url)) {
                throw new RuntimeException("微信下单失败，支付链接为空");
            }
            return url;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Map queryPayStatus(String out_trade_no) {
        Map param=new HashMap();
        param.put("appid", appid);//公众账号ID
        param.put("mch_id", partner);//商户号
        param.put("out_trade_no", out_trade_no);//订单号
        param.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
        String url="https://api.mch.weixin.qq.com/pay/orderquery";
        try {
            String xmlParam = WXPayUtil.generateSignedXml(param, partnerkey);
            HttpClient client=new HttpClient(url);
            client.setHttps(true);
            client.setXmlParam(xmlParam);
            client.post();
            String result = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(result);
            System.out.println(map);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //清除15分钟未支付的订单
    @Override
    public void cleanUnpayedOrders() {
        //先从数据库中获得所有的未支付订单信息
        //需要id payDate setmeal_name member_id phoneNum
        List<Map> list=orderMapper.findUnPayedOrders();

        for (Map stringMap : list) {
            Timestamp pay_Date = (Timestamp) stringMap.get("payDate");
            long pay_date =pay_Date.getTime();
            System.out.println(pay_date);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Calendar cal = Calendar.getInstance();
            Date date = new Date(pay_date);
            cal.setTime(date);
            String payDate= cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.DAY_OF_MONTH);
            System.out.println(payDate);
            try {

                long orderDayeM=pay_date;
                long nowDateM = System.currentTimeMillis();
                long m=(nowDateM-orderDayeM)/1000/60;
                if(m>=15){//订单超过15分钟，从数据库中删除
                    Integer id = (Integer) stringMap.get("id");
                    orderMapper.cleanUnpayedOrderByID(String.valueOf(id));
                    //需要将预约数-1;
                    String setMealName= (String) stringMap.get("setmeal_name");
                    Integer member_id= (Integer) stringMap.get("member_id");
                    String orderDate=orderMapper.findOrderDateBySetmealNameAndMemberId(setMealName, String.valueOf(member_id));
                    orderSettingMapper.releaseOrder(orderDate);
                    //给用户发短信
                    String phoneNum = (String) stringMap.get("phoneNum");
                    SMSUtils.sendCode(phoneNum,"订单已取消");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //需要将预约数-1;

    }

    @Override
    public void updateOrderStauts(String out_trade_no) {
        orderMapper.updateOrderStauts(out_trade_no);
    }

}
